import React, { Component } from 'react';
import classnames from 'classnames';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import { Button, Result, Icon, SearchBar, Popover, Tools, Modal, Avatar, Bubble } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';
import { renderLoading, renderNoSearch } from '../util';
import RouteModal from './RouteModal';

const getLabel = Tools.getLabel;

@withRouter
@inject('listStore')
@observer
class GroupVoteList extends Component {
  static defaultProps = {
    prefixCls: 'group-vote-list'
  }

  componentDidMount() {
    const { listStore: { getGroupVoteList, setStoreState } } = this.props;
    if (window.em) {
      window.em.ready(() => {
        let res = window.em.checkJsApi("getTargetInfo");
        if (res) {
          window.em.getTargetInfo({
            success: function(res) {
              let params = {groupid: res.targetId, isgroup: res.targetType};
              setStoreState(params);
              getGroupVoteList(params);
            },
            fail: function(res) {
              Bubble.error(res.errMsg || '方法请求失败')
            }
          })
        }
      })
    } else {
      getGroupVoteList();
    }
  }

  renderNoData = () => {
    const { history, listStore: { isgroup, newVoteLayout } } = this.props;
    return (
      <div className='group-vote-noData' key='nodata'>
        <Result
          img={<Icon type="document-report" />}
          message={<div>
            <p>{getLabel('506508','暂无投票，快去发布投票吧！')}</p>
            {
              isgroup ? 
                <Button type='primary' onClick={() => history.push(newVoteLayout.path)}>{getLabel('516170','发布新投票')}</Button> :
                null 
            }
          </div>}
        />
      </div>
    )
  }

  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const curCls = `${this.props.prefixCls}-item`;
          return (
            <div className={curCls} key={data.id}>
              <div className={`${curCls}-header`}>
                <Avatar userId={data.createrid} url={data.messagerurlspan || data.messageurl || ''} name={data.createridspan}/>
                <div className={`${curCls}-header-userInfo`}>
                  <div className='user'>
                    <div>
                      <a className='createName' onClick={(e) => {e.stopPropagation(); e.preventDefault(); this.openHrmCard(data.createrid)}}>
                        {data.createridspan || data.creatername}
                      </a>
                      <span className='department'>{data.departmentnamespan}</span>
                    </div>
                    {data.votestatusspan === '0' ? <span className='state ing'>{getLabel('1960','进行中')}</span> : <span className='state end'>{getLabel('22348','已结束')}</span>}
                  </div>
                  <span className='createTime'>{`${data.createdatespan || data.createdate} ${data.createtimespan || data.createtime}`}</span>
                </div>
              </div>
              <div className={`${curCls}-container`}>
                <div className={`${curCls}-container-theme`} dangerouslySetInnerHTML={{__html: data.votethemespan}}/>
                {data.themeimageidspan !== '' && (
                  <div className={`${curCls}-container-themeImage`}><img alt='' src={data.themeimageidspan}/></div>
                )}
                <div className={`${curCls}-container-bottomInfo`}>
                  <span className={`${curCls}-container-cutoff`}>{`${getLabel('18111','截止时间：')} ${data.enddatespan} ${data.endtimespan}`}</span>
                  {
                    data.canDelspan === '1' && (
                      <span className={`${curCls}-container-delete`} onClick={(e) => this.deleteVote(e, data)}><Icon type='delete' size='xxs'/></span>
                    )
                  }
                </div>
              </div>
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  renderSeparator = (section, index) => {
    const { listStore, prefixCls } = this.props;
    const { voteList, shareChoose } = listStore;
    const data = toJS(voteList.data)[index];
    return (
      <div className={`${prefixCls}-item-bottom-wrap`} key={`${section}_${index}`}>
        {!shareChoose && (
          <div className={`${prefixCls}-item-bottom`} onClick={() => this.onRowClick(data)}>
            {
              (data.votestatusspan === '0' && data.hasvotespan === '0') ? <a>{getLabel('506559','立即投票')}</a> : 
              (data.votestatusspan === '1' && data.hasvotespan === '0') ? <a>{getLabel('506560','未投票，查看结果')}</a> : 
              <a>{getLabel('506558','已投票，查看结果')}</a>
            }
          </div>
        )}
      </div>
    )
  }

  openHrmCard = (id) => {
    if (window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')) {
      window.em.openLink({
        url: `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`,
        openType: 2,
        sysId: window.localStorage.emobile_ec_id,
      });
    }
  }

  /* 删除投票 */
  deleteVote = (e, data) => {
    e.preventDefault();
    e.stopPropagation();
    const { listStore } = this.props;
    const { groupchatvotedel } = listStore;
    Modal.alert(getLabel('506504','确定要删除该投票吗?'), '', [
      { text: getLabel('31129','取消') },
      { text: getLabel('826','确定'), onPress: () => groupchatvotedel({votingid: data.id}) }
    ])
  }

  onExtraButtonClick = (key) => {
    const { listStore } = this.props;
    const { setStoreState } = listStore;
    if (key === 'drop') {
      setStoreState({shareVisible: true})
    }
  }

  onSelect = (opt) => {
    const { listStore } = this.props;
    const { setStoreState } = listStore;
    if (opt.key === 'batch') {
      setStoreState({shareVisible: false, shareChoose: true});
    }
  }

  /* 批量分享 */
  handleShare = (selectedRowKeys) => {
    const { listStore: { groupchatvotealert, groupid, isgroup } } = this.props;
    let _groupid = isgroup ? groupid : groupid.split('|')[0]
    Modal.alert(getLabel('516169','确定要分享所选投票吗？'), '', [
      { text: getLabel('31129','取消') },
      { 
        text: getLabel('826','确定'), 
        onPress: () => groupchatvotealert({ votingid: selectedRowKeys.join(), isgroup, groupid: _groupid }, (result) => {
          if (result.voteInfo && result.voteInfo.length > 0) {
            result.voteInfo.forEach((item) => {
              const { votingid, votetheme, enddate, endtime, themeimagesrc } = item
              if (window.em) {
                let checkApi = window.em.checkJsApi("sendMsg");
                if (checkApi) {
                  window.em.sendMsg({
                    targetId: groupid, // 消息会话ID
                    msgType: 10, // 消息类型：1-文本 2-链接 10-E6分享消息
                    msgInfo: {
                      content: votetheme, // 分享标题（必填）
                      desc: `${getLabel('18111','截止时间：')} ${enddate} ${endtime}`, // 分享描述（非必填）
                      canforward: 0, // 消息是否允许转发 1：是（默认） 0：否
                      sharetypename: getLabel('514291','群投票'), //消息类型显示标题，没有则按sharetype显示
                      sharetypeicon: '', //消息类型显示图标
                      sharetypebgcolor: '#9999FF', //消息类型背景颜色，没有则按sharetype显示
                      showimage: themeimagesrc, //消息显示图片地址，没有则不显示图片
                      linkurl: `/spa/groupVote/static4mobile/index.html#/voting/${votingid}`, // 消息链接地址（必填）
                      linkurl_pc: `/spa/smallApp/static/index.html#/main/groupVoting/groupVotingList?id=${votingid}`, //PC端消息链接地址，如果没有则取linkurl值
                      sharetype: 'voting', // 分享数据类型,值有"doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                      shareid: votingid, // 分享的数据ID（必填）
                      opentype: 1, //移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
                      opentype_pc: 1,//PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                    },
                    success: (res) => {
                      // console.log('success',res)
                    },
                    fail: (res) => {
                      // console.log('fail',res)
                    },
                  })
                }
              }
            })
          }
        }) 
      },
    ])
  }

  /* 行点击事件 */
  onRowClick = (rowData) => {
    const { history, listStore: { votingLayout, shareChoose } } = this.props;
    if (!shareChoose) {
      history.push(`${votingLayout.path}/${rowData.id}`)
    }
  }

  renderList = () => {
    const { prefixCls, history, listStore } = this.props;
    const { newVoteLayout, setStoreState, shareVisible, isgroup,voteList, doShareCancel, doShareSelectAll, doShareSelectNone, getGroupVoteList, shareChoose, isSearch, listSearchName } = listStore;
    const datas = toJS(voteList.data);
    const themeSelectedKeys = toJS(voteList.selectedRowKeys);
    const more = (
      <Popover
        mask
        visible={shareVisible}
        overlay={[<Popover.Item key='batch' >{getLabel('500410','批量操作')}</Popover.Item>]}
        onVisibleChange={v => setStoreState({shareVisible: v})}
        onSelect={this.onSelect}
      >
        <Icon key="ellipsis" type="ellipsis" />
      </Popover>
    )
    const extraButton = [{ key: 'drop', show: more }];
    const listCls = classnames({
      [`${prefixCls}-container`]: true,
      'showCheck': shareChoose,
      'isgroup': !isgroup,
    });
    return (
      <React.Fragment>
        <SearchBar 
          placeholder={getLabel('516193','请输入群投票名称')}
          showExtraButton
          extraButton={extraButton}
          onExtraButtonClick={this.onExtraButtonClick}
          value={listSearchName}
          onChange={v => setStoreState({listSearchName: v})}
          onSubmit={v => {
            setStoreState({isSearch: true})
            getGroupVoteList({groupvotename: v})
          }}
        />
        {
          shareChoose && (
            <div className={`${prefixCls}-top`}>
              <span className={`${prefixCls}-top-cancel`} onClick={doShareCancel}>{getLabel('31129','取消')}</span>
              <span>{getLabel(31503,"已选择")}{themeSelectedKeys.length}{getLabel('24683','条记录')}</span>
              {themeSelectedKeys.length !== datas.length ?
                <span className={`${prefixCls}-top-all`} onClick={doShareSelectAll}>{getLabel(556, '全选')}</span> :
                <span className={`${prefixCls}-top-all`} onClick={doShareSelectNone}>{getLabel(387379,"取消全选")}</span>
              }
            </div>
          )
        }
        <div className={listCls}>
          {
            datas.length === 0 && isSearch ? renderNoSearch() : (
              <ListViewPage.Normal
                store={voteList}
                customHeight={'100%'}
                showCheck={shareChoose}
                isRowClickCheck={shareChoose}
                getTemplate={this.getTemplate}
                renderSeparator={this.renderSeparator}
                onRowClick={this.onRowClick}
                onRefresh={() => getGroupVoteList()}
              />
            )
          }
        </div>
        <div className={`${prefixCls}-publish`}>
          {
            shareChoose ? <Button type='primary' disabled={themeSelectedKeys.length === 0} onClick={() => this.handleShare(themeSelectedKeys)}>{getLabel('516194','批量分享')}</Button> :
            isgroup ? <Button type='primary' onClick={() => history.push(newVoteLayout.path)}>{getLabel('516170','发布新投票')}</Button> :
            null
          }
        </div>
      </React.Fragment>
    )
  }

  render () {
    const { prefixCls, listStore } = this.props;
    const { voteListLoading } = listStore;
    const { voteList, isSearch } = listStore;
    const datas = toJS(voteList.data);
    let child = null;
    if (voteListLoading) child = renderLoading;
    if (!voteListLoading && datas.length === 0 && !isSearch) child = this.renderNoData();
    else child = this.renderList();
    return (
      <div className={prefixCls}>
        {child}
        <RouteModal/>
      </div>
    )
  }
}

export default GroupVoteList